package com.iwunu.gateway.service.impl;

import org.springframework.stereotype.Service;

import com.iwunu.auth.config.JwtConfig;
import com.iwunu.auth.util.JwtTokenUtil;
import com.iwunu.auth.vo.JwtUserVo;
import com.iwunu.gateway.service.TokenService;
import com.iwunu.gateway.vo.TokenVo;

import javax.annotation.Resource;

/**
 * @author harvey
 * @date 2019-04-21 10:55
 * @desc
 */
@Service
public class TokenServiceImpl implements TokenService {

    @Resource
    private JwtTokenUtil jwtTokenUtil;

    @Override
    public TokenVo getToken(String id) {
        JwtUserVo jwtUserVo = new JwtUserVo();
        jwtUserVo.setUsername(id);
        jwtUserVo.setPassword("iwunu2021");
        TokenVo tokenVo = new TokenVo("Bearer " + jwtTokenUtil.create(jwtUserVo));
        return tokenVo;
    }

    @Override
    public TokenVo reshToken(String Authorization) {
        String phone = parseToken(Authorization);
        return getToken(phone);
    }

    @Override
    public String parseToken(String Authorization) {
        JwtConfig jwtConfig = jwtTokenUtil.getJwtConfig();
        String token = Authorization.substring(jwtConfig.headerPrefixLength(),Authorization.length());
        JwtUserVo jwtUserVo = jwtTokenUtil.parse(token);
        return jwtUserVo.getUsername();
    }
    
    @Override
    public TokenVo getOrgToken(String id) {
        JwtUserVo jwtUserVo = new JwtUserVo();
        jwtUserVo.setUsername(id);
        jwtUserVo.setPassword("iwunu2021");
        TokenVo tokenVo = new TokenVo("Org " + jwtTokenUtil.create(jwtUserVo));
        return tokenVo;
    }

    @Override
    public TokenVo reshOrgToken(String Authorization) {
        String phone = parseToken(Authorization);
        return getToken(phone);
    }

    @Override
    public String parseOrgToken(String Authorization) {
        JwtConfig jwtConfig = jwtTokenUtil.getJwtConfig();
        String token = Authorization.substring(jwtConfig.headerPrefixLength());
        JwtUserVo jwtUserVo = jwtTokenUtil.parse(token);
        return jwtUserVo.getUsername();
    }
	@Override
	public String parseDeviceToken(String Authorization) {
		Authorization = Authorization.replace(":", "");
	  return Authorization.substring(Authorization.length()-8,Authorization.length()).toLowerCase();
	}
}
